package network

import (
	"fmt"
	"gomir/mlog"
	"net"
)

type Network struct{}

var _network *Network = nil

func GetNetwork() *Network {
	if _network == nil {
		_network = &Network{}
	}
	return _network
}

func (s *Network) Start() {
	if MsgHandler == nil {
		panic("MsgHandler is nil")
	}

	mlog.Info("Server start")

	go func() {
		addr, err := net.ResolveTCPAddr("tcp4", "0.0.0.0:7000")
		if err != nil {
			mlog.Error("net.ResolveTCPAddr err:", err)
			return
		}
		listener, err := net.ListenTCP("tcp4", addr)
		if err != nil {
			mlog.Error("net.ListenTCP err:", err)
			return
		}
		mlog.Info("listenning at :7000")

		for {
			conn, err := listener.AcceptTCP()
			if err != nil {
				mlog.Error("listener.AcceptTCP err:", err)
				continue
			}
			mlog.Info("Accept Client=", conn.RemoteAddr().String())
			clientConn := NewClientConn(conn)
			go clientConn.Start()
		}
	}()
}

func (s *Network) Stop() {
	fmt.Println("Server Stop")
}
